# -*- coding: utf-8 -*-
from Base import *
from BaseUI import *
from MyPlayer import *
from api import *


Navigation = ["推荐", "歌单", "主播电台", "排行榜", "播放器"]
NavigationId = [400, 401, 402, 403, 404]


def openWindow(window_name, session=None, **kwargs):
    windowFile = '%s.xml' % window_name
    if window_name == 'discover':
        w = DiscoverWindow(windowFile, cwd, "Default", session=session, **kwargs)
    elif window_name == 'playlist':
        w = PlaylistWindow(windowFile, cwd, "Default", session=session, **kwargs)
    else:
        w = BaseWindow(windowFile, cwd, "Default", session=session, **kwargs)
    w.doModal()
    del w


class DiscoverWindow(BaseWindow):
    def __init__(self, *args, **kwargs):
        self.toplistMenu = [{"pic": "toplist_new.jpg", "label": "云音乐新歌榜", "label2": "每天更新", "id": 3779629},
                            {"pic": "toplist_hot.jpg", "label": "云音乐热歌榜", "label2": "每周四更新", "id": 3778678},
                            {"pic": "toplist_original.jpg", "label": "云音乐原创歌曲榜", "label2": "每周四更新", "id": 2884035},
                            {"pic": "toplist_speed.jpg", "label": "云音乐飙升榜", "label2": "每天更新", "id": 19723756}]
        self.toplistMenu2 = [{"pic": "toplist_acg.jpg", "label": "云音乐ACG音乐榜", "label2": "每周四更新", "id": 71385702},
                             {"pic": "toplist_classical.jpg", "label": "云音乐古典音乐榜", "label2": "每周四更新", "id": 71384707},
                             {"pic": "toplist_rockin.jpg", "label": "云音乐电音榜", "label2": "每周四更新", "id": 10520166},
                             {"pic": "toplist_uk.jpg", "label": "UK排行榜周榜", "label2": "每周五更新", "id": 180106},
                             {"pic": "toplist_billboard.jpg", "label": "美国Billboard周榜", "label2": "每周三更新", "id": 60198},
                             {"pic": "toplist_beatport.jpg", "label": "Beatport全球电子舞曲榜", "label2": "每周四更新", "id": 3812895},
                             {"pic": "toplist_nrj.jpg", "label": "法国 NRJ Vos Hits 周榜", "label2": "每周五更新", "id": 27135204},
                             {"pic": "toplist_ktv.jpg", "label": "KTV唛榜", "label2": "每周五更新", "id": 21845217},
                             {"pic": "toplist_itunes.jpg", "label": "iTunes榜", "label2": "每周一更新", "id": 11641012},
                             {"pic": "toplist_oricon.jpg", "label": "日本Oricon周榜", "label2": "每周三更新", "id": 60131},
                             {"pic": "toplist_melon.jpg", "label": "韩国Melon排行榜周榜", "label2": "每周一更新", "id": 3733003},
                             {"pic": "toplist_melon.jpg", "label": "韩国Melon原声周榜", "label2": "每周一更新", "id": 46772709},
                             {"pic": "toplist_mnet.jpg", "label": "韩国Mnet排行榜周榜", "label2": "每周一更新", "id": 60255},
                             {"pic": "toplist_hitfm.jpg", "label": "Hit FM Top榜", "label2": "每周一更新", "id": 120001},
                             {"pic": "toplist_hit.jpg", "label": "台湾Hito排行榜", "label2": "每周一更新", "id": 112463},
                             {"pic": "toplist_tw.jpg", "label": "中国TOP排行榜（港台榜）", "label2": "每周一更新", "id": 112504},
                             {"pic": "toplist_nd.jpg", "label": "中国TOP排行榜（内地榜）", "label2": "每周一更新", "id": 64016},
                             {"pic": "toplist_lh.jpg", "label": "香港电台中文歌曲龙虎榜", "label2": "每周五更新", "id": 10169002},
                             {"pic": "toplist_jq.jpg", "label": "华语金曲榜", "label2": "每周一更新", "id": 4395559},
                             {"pic": "toplist_xh.jpg", "label": "中国嘻哈榜", "label2": "每周五更新", "id": 1899724}]
        self.navInited = False
        self.selectedNavigation = 0
        self.hotInited = False
        self.playlistInited = False
        self.toplistInited = False
        BaseWindow.__init__(self, args, kwargs)

    def onInit(self):
        BaseWindow.onInit(self)
        self.showBusy()
        self.initNavigation()

        log("it`s main window")
        self.updateNavigation()
        for id in NavigationId:
            if id != NavigationId[self.selectedNavigation]:
                self.getControl(id).setEnabled(False)
                self.getControl(id).setVisible(False)
        self.getControl(510).getListItem(self.selectedNavigation).select(True)

        self.initPlayerlist()
        self.initHot()
        self.initPlaylist()
        self.hideBusy()

    def initNavigation(self):
        if self.navInited:
            return
        for item in Navigation:
            listitem = xbmcgui.ListItem(label=item)
            self.getControl(510).addItem(listitem)
        self.getControl(510).getListItem(0).select(True)
        self.navInited = True

    def initPlayerlist(self):
        playlist = player.getPlaylist()
        if playlist == None:
            return
        control = self.getControl(4000)
        control.reset()
        for i in range(len(playlist)):
            item = playlist[i]
            # log("label=" + item.getLabel())
            control.addItem(item)

    def initHot(self):
        if self.hotInited:
            return
        respData = api.getHot()
        if respData != None and respData["code"] == 200:
            hotspotList = respData["/api/discovery/hotspot"]["data"]
            for item in hotspotList:
                listitem = xbmcgui.ListItem(label=item['name'], thumbnailImage=item['picUrl'])
                listitem.setProperty("id", str(item["id"]))
                self.getControl(520).addItem(listitem)

            newMusicList = respData["/api/v1/discovery/new/songs"]["data"]
            num = 1
            control = self.getControl(530)
            for item in newMusicList:
                seq = str(num)
                if num < 10:
                    seq = "0" + str(num)
                listitem = xbmcgui.ListItem(label=seq + "  " + item['name'], label2=item['artists'][0]['name'],
                                            thumbnailImage=None)
                listitem.setProperty("mp3Url", str(item["mp3Url"]))
                listitem.setProperty("name", str(item["name"]))
                listitem.setProperty("picUrl", str(item["album"]["picUrl"]))
                listitem.setProperty("artistsName", str(item["artists"][0]["name"]))
                listitem.setProperty("albumName", str(item["album"]["name"]))
                control.addItem(listitem)
                num += 1
        self.hotInited = True

    def initPlaylist(self):
        if self.playlistInited:
            return

        respData = api.getPlaylist()
        if respData is not None and respData["code"] == 200:
            playlist = respData["playlists"]
            for item in playlist:
                listitem = xbmcgui.ListItem(label=item['name'], thumbnailImage=item['coverImgUrl'])
                listitem.setProperty("id", str(item["id"]))
                self.getControl(1000).addItem(listitem)
        self.playlistInited = True

    def initToplist(self):
        if self.toplistInited:
            return
        self.showBusy()
        control = self.getControl(3000)
        for data in self.toplistMenu:
            listitem = xbmcgui.ListItem(label=data["label"], label2=data["label2"], thumbnailImage=data["pic"])
            listitem.setProperty("id", str(data["id"]))
            control.addItem(listitem)
        self.refreshToplist()

        control = self.getControl(3030)
        for data in self.toplistMenu2:
            listitem = xbmcgui.ListItem(label=data["label"], label2=data["label2"], thumbnailImage=data["pic"])
            listitem.setProperty("id", str(data["id"]))
            control.addItem(listitem)

        self.toplistInited = True
        self.hideBusy()

    def refreshToplist(self, id=3779629):
        self.showBusy()
        data = api.getToplist(id)
        if data is not None:
            toplistControl = self.getControl(3010)
            toplistControl.reset()
            for item in data:
                id = item["id"]
                name = item["name"]
                mp3Url = item["mp3Url"]
                duration = item["duration"]
                picUrl = item["album"]["picUrl"]
                artistsName = item["artists"][0]["name"]
                albumName = item["album"]["name"]
                listitem = xbmcgui.ListItem(label=name, label2=artistsName)
                listitem.setProperty("mp3Url", mp3Url)
                listitem.setProperty("name", name)
                listitem.setProperty("picUrl", picUrl)
                listitem.setProperty("artistsName", artistsName)
                listitem.setProperty("albumName", albumName)
                toplistControl.addItem(listitem)
        self.hideBusy()

    def onClick(self, controlId):
        BaseWindow.onClick(self, controlId)
        if controlId == 510:
            self.updateNavigation()
        elif controlId == 520:
            listitem = self.getControl(controlId).getSelectedItem()
            id = listitem.getProperty("id")
            openWindow('playlist', self.session, id=id)
        elif controlId == 530:
            playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            playlist.clear()
            listitem = self.getControl(controlId).getSelectedItem()
            mp3Url = listitem.getProperty("mp3Url")
            name = listitem.getProperty("name")
            picUrl = listitem.getProperty("picUrl")
            albumName = listitem.getProperty("albumName")
            artistsName = listitem.getProperty("artistsName")
            listitem = xbmcgui.ListItem(label=name, label2=artistsName, thumbnailImage=picUrl)
            listitem.setInfo('music', {'Title': name, 'Genre': albumName})
            playlist.add(mp3Url, listitem)
            player.play(playlist, arg=mp3Url)
        elif controlId == 540:
            list = self.getControl(530)
            playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            playlist.clear()
            for i in range(list.size()):
                listitem = list.getListItem(i)
                mp3Url = listitem.getProperty("mp3Url")
                name = listitem.getProperty("name")
                picUrl = listitem.getProperty("picUrl")
                albumName = listitem.getProperty("albumName")
                artistsName = listitem.getProperty("artistsName")
                listitem = xbmcgui.ListItem(label=name, label2=artistsName, thumbnailImage=picUrl)
                listitem.setInfo('music', {'Title': name, 'Genre': albumName})
                playlist.add(mp3Url, listitem)
            player.play(playlist, arg="new music")
        elif controlId == 1000:
            listitem = self.getControl(controlId).getSelectedItem()
            id = listitem.getProperty("id")
            log("id=" + id)
            openWindow('playlist', self.session, id=id)
        elif controlId == 3000 or controlId == 3030:
            listitem = self.getControl(controlId).getSelectedItem()
            id = listitem.getProperty("id")
            self.refreshToplist(int(id))
        elif controlId == 3010:
            playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            playlist.clear()
            listitem = self.getControl(controlId).getSelectedItem()
            mp3Url = listitem.getProperty("mp3Url")
            name = listitem.getProperty("name")
            picUrl = listitem.getProperty("picUrl")
            albumName = listitem.getProperty("albumName")
            artistsName = listitem.getProperty("artistsName")
            listitem = xbmcgui.ListItem(label=name, label2=artistsName, thumbnailImage=picUrl)
            listitem.setInfo('music', {'Title': name, 'Genre': albumName})
            playlist.add(mp3Url, listitem)
            player.play(playlist, arg=mp3Url)
        elif controlId == 3020:
            list = self.getControl(3010)
            playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            playlist.clear()
            for i in range(list.size()):
                listitem = list.getListItem(i)
                mp3Url = listitem.getProperty("mp3Url")
                name = listitem.getProperty("name")
                picUrl = listitem.getProperty("picUrl")
                albumName = listitem.getProperty("albumName")
                artistsName = listitem.getProperty("artistsName")
                listitem = xbmcgui.ListItem(label=name, label2=artistsName, thumbnailImage=picUrl)
                listitem.setInfo('music', {'Title': name, 'Genre': albumName})
                playlist.add(mp3Url, listitem)
            player.play(playlist, arg="new music")

    def updateNavigation(self):
        if self.getFocusId() == 510:
            newSelectedNavigation = self.getControl(510).getSelectedPosition()
            if self.selectedNavigation != newSelectedNavigation:
                self.getControl(510).getListItem(self.selectedNavigation).select(False)
                self.getControl(NavigationId[self.selectedNavigation]).setEnabled(False)
                self.getControl(NavigationId[self.selectedNavigation]).setVisible(False)

                self.selectedNavigation = newSelectedNavigation
                log("selectedNavigation=" + str(self.selectedNavigation))
                log(NavigationId[self.selectedNavigation])

                if self.selectedNavigation == 0:
                    pass
                elif self.selectedNavigation == 3:
                    self.initToplist()
                elif self.selectedNavigation == 4:
                    self.initPlayerlist()

                log("init end")
                self.getControl(NavigationId[self.selectedNavigation]).setEnabled(True)
                self.getControl(NavigationId[self.selectedNavigation]).setVisible(True)
                self.getControl(510).getListItem(self.selectedNavigation).select(True)

    def onAction(self, action):
        BaseWindow.onAction(self, action)
        if action.getId() == ACTION_MOVE_LEFT or action.getId() == ACTION_MOVE_RIGHT:
            self.updateNavigation()
        return


class PlaylistWindow(BaseWindow):
    def __init__(self, *args, **kwargs):
        self.id = kwargs.get("id")
        BaseWindow.__init__(self, args, kwargs)

    def onInit(self):
        BaseWindow.onInit(self)
        self.showBusy()
        try:
            self.initData()
        except Exception, e:
            print e
            log("load playlist error")
        self.hideBusy()

    def initData(self):
        data = api.getPlaylistDetail(self.id)
        self.getControl(1000).setImage(data["result"]["coverImgUrl"])
        self.getControl(1001).setLabel(data["result"]["name"])
        self.getControl(1002).setImage(data["result"]["creator"]["avatarUrl"])
        self.getControl(1003).setLabel(str(data["result"]["creator"]["nickname"]))
        self.getControl(1004).setLabel(str(data["result"]["createTime"]))
        playlist = data["result"]["tracks"]
        num = 1
        control = self.getControl(1010)
        for item in playlist:
            seq = str(num)
            if num < 10:
                seq = "0" + str(num)
            listitem = xbmcgui.ListItem(label=seq + "  " + item['name'], label2=item["artists"][0]["name"],
                                        thumbnailImage=None)
            listitem.setProperty("mp3Url", str(item["mp3Url"]))
            listitem.setProperty("name", str(item["name"]))
            listitem.setProperty("picUrl", str(item["album"]["picUrl"]))
            listitem.setProperty("artistsName", str(item["artists"][0]["name"]))
            listitem.setProperty("albumName", str(item["album"]["name"]))
            control.addItem(listitem)
            num += 1
        tags = data["result"]["tags"]
        log("start load tags")
        for item in tags:
            log(str(item))
            listitem = xbmcgui.ListItem(label=str(item), thumbnailImage=None)
            self.getControl(1020).addItem(listitem)

        self.getControl(1030).setLabel(str(data["result"]["description"]))

    def onClick(self, controlId):
        BaseWindow.onClick(self, controlId)
        if controlId == 1005:
            list = self.getControl(1010)
            playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            playlist.clear()
            for i in range(list.size()):
                listitem = list.getListItem(i);
                mp3Url = listitem.getProperty("mp3Url")
                name = listitem.getProperty("name")
                picUrl = listitem.getProperty("picUrl")
                albumName = listitem.getProperty("albumName")
                artistsName = listitem.getProperty("artistsName")
                listitem = xbmcgui.ListItem(label=name, label2=artistsName, thumbnailImage=picUrl)
                listitem.setInfo('music', {'Title': name, 'Genre': albumName})
                playlist.add(mp3Url, listitem)
            player.play(playlist, arg="new music")
        if controlId == 1010:
            listitem = self.getControl(controlId).getSelectedItem()
            mp3Url = listitem.getProperty("mp3Url")
            playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
            playlist.clear()
            mp3Url = listitem.getProperty("mp3Url")
            name = listitem.getProperty("name")
            picUrl = listitem.getProperty("picUrl")
            albumName = listitem.getProperty("albumName")
            artistsName = listitem.getProperty("artistsName")
            listitem = xbmcgui.ListItem(label=name, label2=artistsName, thumbnailImage=picUrl)
            listitem.setInfo('music', {'Title': name, 'Genre': albumName})
            playlist.add(mp3Url, listitem)
            player.play(playlist, arg=mp3Url)

    def onAction(self, action):
        return BaseWindow.onAction(self, action)
